﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace KrileUpdater.Migrate._095
{
    public class Migrator
    {
        public string MigrateState(string homeDir)
        {
            try
            {
                var originFile = Path.Combine(homeDir, "krile.state");
                var destFile = Path.Combine(homeDir, "krile.dynamic");
                if (!File.Exists(originFile))
                    return "Migration target file (krile.state) not found.";
                if (!File.Exists(originFile) || File.Exists(destFile))
                    return "Migration destination file (krile.dynamic) is already existed.";

                using (var sr = new StreamReader(originFile))
                {
                    string orgstr = sr.ReadToEnd();
                    string newStr = orgstr.Replace(
                            "<_State xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">",
                            "<_DynamicLoad xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
                            ).Replace(
                            "</_State>",
                            "</_DynamicLoad>"
                            );
                    using (var sw = new StreamWriter(destFile))
                    {
                        sw.Write(newStr);
                    }
                }
                return "Migration finished successfully.";
            }
            catch (Exception e)
            {
                return "Migration error:" + e.Message + Environment.NewLine + e.ToString();
            }
        }
    }
}
